using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Core.Mapping;
using Core.Graphics;
using System.Drawing.Imaging;

namespace WorldEditor.Import.FromImage
{
    public partial class MapFromImage : Form
    {
        protected TileWorld _World;

        public MapFromImage(TileWorld World)
        {
            _World = World;

            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (ofdImage.ShowDialog() == DialogResult.OK)
            {
                txtImagePath.Text = ofdImage.FileName;
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            imgSource.Image = System.Drawing.Image.FromFile(txtImagePath.Text);
        }

        private void btnRender_Click(object sender, EventArgs e)
        {
            Render();
        }

        private void Render()
        {
            int sX = Convert.ToInt32(txtX.Text);
            int sY = Convert.ToInt32(txtY.Text);

            Microsoft.Xna.Framework.Point spt = new Microsoft.Xna.Framework.Point(sX, sY);

            Bitmap bmp = new Bitmap(imgSource.Image);

            for (int y = 0; y < bmp.Height; y++)
            {
                for (int x = 0; x < bmp.Width; x++)
                {
                    Color pcl = bmp.GetPixel(x, y);

                    int argb = pcl.ToArgb();

                    if(argb == 0)
                    {
                        _World.SetTileAtLocation(new Microsoft.Xna.Framework.Point(sX + x, sY + y),
                            MapLayerTypes.Base, new Tile(TileSetCollection.GlobalTerrainTileSets[0].Tiles[0].SpriteID));
                    }
                    else if (argb == Color.Black.ToArgb())
                    {
                        _World.SetTileAtLocation(new Microsoft.Xna.Framework.Point(sX + x, sY + y),
                            MapLayerTypes.Terrain, new Tile(TileSetCollection.GlobalTerrainTileSets[0].Tiles[1].SpriteID));
                    }
                    else if(argb == Color.White.ToArgb())
                    {
                        _World.SetTileAtLocation(new Microsoft.Xna.Framework.Point(sX + x, sY + y),
                            MapLayerTypes.Terrain, new Tile(TileSetCollection.GlobalTerrainTileSets[0].Tiles[2].SpriteID));
                    }
                    else
                    {
                        _World.SetTileAtLocation(new Microsoft.Xna.Framework.Point(sX + x, sY + y),
                            MapLayerTypes.Terrain, new Tile(TileSetCollection.GlobalTerrainTileSets[0].Tiles[3].SpriteID));
                    }
                }
            }
        }
    }
}